package com.quartz.config;

import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.io.IOException;
import java.util.Properties;

/**
 * @描述: quartz的配置类:
 * 1. SchedulerFactoryBean
 * 2. Scheduler类
 * @类名:
 * @作者: yangshuang
 * @创建时间: 2017/8/17 19:12
 * @版本: v1.0
 */
@Configuration
public class QuartzConfig {

    @Autowired
    private SpringBeanJobFactory springBeanJobFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean()  {
        SchedulerFactoryBean schedulerFactoryBean = null;
        try {
            schedulerFactoryBean = new SchedulerFactoryBean();
            schedulerFactoryBean.setQuartzProperties(quartzProperties());
            //拔job交给spring管理
            schedulerFactoryBean.setJobFactory(springBeanJobFactory);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return schedulerFactoryBean;
    }


    /**
     * 加载指定的quartz.properties
     *
     * @return
     * @throws IOException
     */
    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();


    }

    @Bean
    public Scheduler scheduler(){
        return schedulerFactoryBean().getScheduler();
    }


}
